<template>
  <div>
    <el-upload
      class="upload-file text-center"
      drag
      ref="upload"
      accept=".pdf,.doc,.docx,.xls,.xlsx,.txt"
      action="/myapp/api/file/search-file"
      :show-file-list="true"
      :auto-upload="false"
      :file-list="uploadFileList"
      :on-remove="handleFileRemove"
      :on-change="handleUploadChange"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
    </el-upload>

    <div class="mt30 text-center">
      <el-form :inline="true" ref="fromRef" :rules="rules" :model="formData" @submit.native.prevent="handleFormSubmit">
        <el-form-item label="附件类型：" prop="tags">
          <el-select v-model="formData.tags" placeholder="请选择附件类型">
            <el-option v-for="(it, i) of attachmentTypes" :key="i" :value="it.className"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-right: 0">
          <el-button type="primary" native-type="submit" :disabled="!uploadFileList.length">上传</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// import { createAttachmentTypes } from '@/views/AttachmentManagement/components/create'
import { createFormRules } from './create'
import { apiUploadFile } from '@/api/AttachmentManagement/index'
// create
import { createForm } from './create'

export default {
  name: 'UploadFile',

  props: {
    attachmentTypes: {
      type: Array,
      default() {
        return []
      }
    }
  },

  data() {
    return {
      formData: createForm(),
      rules: createFormRules(),

      uploadFileList: [],

      // attachmentTypes: createAttachmentTypes()
    }
  },

  methods: {
    handleFormSubmit() {
      this.$refs.fromRef
        .validate()
        .then(res => {
          // console.log('res', res, this.uploadFileList, this.formData)
          this.uploadFile(this.uploadFileList[0].raw, this.formData)
        })
        .catch(err => {
          console.log('err', err)
        })
    },

    resetForm() {
      this.formData = createForm()
      this.uploadFileList = []
    },

    handleUploadChange(file) {
      // console.log(file)
      if (this.uploadFileList.length > 0) {
        this.uploadFileList.pop()
      }
      this.uploadFileList.push(file)
    },

    handleFileRemove(file) {
      this.uploadFileList = this.uploadFileList.filter(it => it !== file)
    },

    uploadFile(file, data) {
      apiUploadFile(file, data).then(res => {
        // console.log('apiUploadFile', res);
        this.$message.success(res.msg)
        this.$emit('upload-success')
        window.setTimeout(this.resetForm, 50)
      })
      .catch(err => {
        console.log(err);
        this.$message.error('上传失败')
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
